﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Ext.Net;
using VTV.TaskManagementSystem.Entities;
using VTV.TaskManagementSystem.BusinessLogic;
using VTV.TaskManagementSystem.Common.Constant;

namespace VTV.TaskManagementSystem.WebApp.Admin.Employees
{
    public partial class List : System.Web.UI.Page
    {
        private static bool _isUpdate;
        private static int _employeeID;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] == null || Session["UserName"] == null || Session["RoleLevel"] == null)
            {
                Response.Redirect("~/Admin/Login.aspx?return=/Admin/Employees/List.aspx");
            }
        }

        protected void storeEmployee_OnReadData(object sender, StoreReadDataEventArgs e)
        {
            var start = e.Start;
            var limit = e.Limit;

            var source = new BusinessLogic.Employee().GetAll(start, limit);
            var total = new BusinessLogic.Employee().GetCount();

            if (source != null && source.Any() && total != null)
            {
                var data = new Paging<Entities.Employee>(source, (int)total);

                e.Total = data.TotalRecords;

                this.storeEmployee.DataSource = data.Data;
                this.storeEmployee.DataBind();
            }
        }

        protected void gridEmployee_OnCommand(object sender, DirectEventArgs e)
        {
            _employeeID = Convert.ToInt32(e.ExtraParams["EmployeeID"]);
            var command = e.ExtraParams["Command"];

            if (command.Equals("Edit"))
            {
                _isUpdate = true;
                var obj = new BusinessLogic.Employee();
                var entity = obj.GetEmployee(_employeeID);

                if (entity != null && string.IsNullOrEmpty(obj.ErrorMessage))
                {
                    if (!this.SetValue(entity))
                    {
                        this.btnSave.Enable(false);
                        X.Msg.Notify(AuditInfoMessage.AUDIT_TITLE_VN, AuditInfoMessage.TRANSFER_FAILSE_VN + "<BR>" + AuditHelpMessage.PLS_BACK_LASTER).Show();
                    }
                }

                this.windowDetailEmployee.Icon = Icon.UserEdit;
                this.windowDetailEmployee.Title = "Cập nhật thông tin";
                this.windowDetailEmployee.Show();
            }
            else
            {
                X.Msg.Confirm(AuditInfoMessage.AUDIT_TITLE_VN, AuditInfoMessage.DELETE_CONFIRM_VN,
                              new MessageBoxButtonsConfig()
                                  {
                                      Yes = new MessageBoxButtonConfig
                                                {
                                                    Text = "Xác nhận",
                                                    Handler = "Employee.List.DeleteEmployee()"
                                                },
                                      No = new MessageBoxButtonConfig
                                               {
                                                   Text = "Quay lại"
                                               }

                                  }).Show();
            }
        }

        [DirectMethod(Namespace = "Employee.List")]
        public void DeleteEmployee()
        {
            var obj = new BusinessLogic.Employee();
            var entity = obj.GetEmployee(_employeeID);
            if (entity != null && string.IsNullOrEmpty(obj.ErrorMessage))
            {
                var result = obj.Delete(entity);

                if (result)
                {
                    this.storeEmployee.Reload();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.DELETE_SUCCESS_VN).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
            //X.Msg.Notify("delete", _employeeID.ToString()).Show();
        }

        protected void btnSave_Click(object sender, DirectEventArgs e)
        {
            var obj = new BusinessLogic.Employee();
            var entityData = new Entities.Employee
                                 {
                                     EmployeeID = !String.IsNullOrEmpty(EmployeeID.Text.Trim())? Convert.ToInt32(EmployeeID.Text) : 0,
                                     FullName = String.IsNullOrEmpty(txtFullName.Text.Trim()) ? string.Empty : txtFullName.Text.Trim(),
                                     Note = String.IsNullOrEmpty(txtNote.Text.Trim()) ? string.Empty : txtNote.Text.Trim(),
                                     BirthDate = txtBirthDate.IsEmpty ? null : (DateTime?)txtBirthDate.Value,
                                     Address = String.IsNullOrEmpty(txtAddress.Text.Trim()) ? string.Empty : txtAddress.Text.Trim(),
                                     Email = String.IsNullOrEmpty(txtEmail.Text.Trim()) ? string.Empty : txtEmail.Text.Trim(),
                                     Phone = String.IsNullOrEmpty(txtPhone.Text.Trim()) ? string.Empty : txtPhone.Text.Trim(),
                                     IsActive = chkIsActive.Checked
                                 };

            if (_isUpdate)
            {
                var result = obj.Update(entityData);

                if (result)
                {
                    this.storeEmployee.Reload();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.UPDATE_SUCCESS_DETAIL_VN.Replace("{0}", txtFullName.Text)).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
            else
            {
                var result = obj.AddNew(entityData);

                if (result)
                {
                    this.storeEmployee.Reload();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.INSERT_SUCCESS_DETAIL_VN.Replace("{0}", txtFullName.Text)).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
        }

        protected void btnAdd_Click(object sender, DirectEventArgs e)
        {
            _isUpdate = false;
            this.windowDetailEmployee.Icon = Icon.UserAdd;
            this.windowDetailEmployee.Title = "Thêm mới";
            this.windowDetailEmployee.Show();
        }

        private bool SetValue(Entities.Employee entity)
        {
            try
            {
                txtFullName.Text = entity.FullName;
                txtAddress.Text = entity.Address;
                txtBirthDate.Value = entity.BirthDate;
                txtEmail.Text = entity.Email;
                txtNote.Text = entity.Note;
                txtPhone.Text = entity.Phone;
                chkIsActive.Checked = entity.IsActive;
                EmployeeID.Text = entity.EmployeeID.ToString();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}